import { changeAntdTheme } from "mini-dynamic-antd-theme";
import { getSiteInfo, getInitInfo } from "@/api/siteInfo";

const actionTypes = {
  // 用户登录信息
  CREATE_USER_LOGIN_INFO: "CREATE_USER_LOGIN_INFO",
  // 用户退出
  DETELE_USER_LOGIN_INFO: "DETELE_USER_LOGIN_INFO",
  // 更新创建token
  UPDATE_GOLBAL_USER_TOKEN: "UPDATE_GOLBAL_USER_TOKEN",
  // 更新主题
  UPDATE_GLOABL_THEME_COLOR: "UPDATE_GLOABL_THEME_COLOR",
  // 设置站点信息
  UPDATE_GLOBAL_SITE_INFO: "UPDATE_GLOBAL_SITE_INFO",
  // 设置初始信息
  UPDATE_GLOBAL_INIT_INFO: "UPDATE_GLOBAL_INIT_INFO"
};

export default {
  namespaced: true,
  state: {
    // 用户信息
    userInfo: {
      name: ""
    },
    // 登录token
    token: "",
    // 全局配置
    config: {
      themeColor: "#1890ff"
    },
    // 站点信息
    siteInfo: {},
    // 初始信息
    siteInitInfo: {}
  },
  mutations: {
    [actionTypes.CREATE_USER_LOGIN_INFO](state, payload) {
      state.userInfo = payload;
    },
    [actionTypes.DETELE_USER_LOGIN_INFO](state) {
      state.userInfo = {};
      state.token = "";
    },
    [actionTypes.UPDATE_GOLBAL_USER_TOKEN](state, payload) {
      state.token = payload;
    },
    [actionTypes.UPDATE_GLOABL_THEME_COLOR](state, payload) {
      state.config.themeColor = payload;
    },
    [actionTypes.UPDATE_GLOBAL_SITE_INFO](state, payload) {
      state.siteInfo = payload;
    },
    [actionTypes.UPDATE_GLOBAL_INIT_INFO](state, payload) {
      state.siteInfo = { ...state.siteInfo, ...payload };
      state.siteInitInfo = payload;
    }
  },
  actions: {
    // 登录
    login({ commit }, payload) {
      commit(actionTypes.CREATE_USER_LOGIN_INFO, payload);
    },
    // 退出
    logout({ commit }) {
      commit(actionTypes.DETELE_USER_LOGIN_INFO);
    },
    // 创建更新token
    setToken({ commit }, payload) {
      commit(actionTypes.UPDATE_GOLBAL_USER_TOKEN, payload);
    },
    // 改变主题色
    changeThemeColor({ commit }, payload) {
      changeAntdTheme(payload);
      commit(actionTypes.UPDATE_GLOABL_THEME_COLOR, payload);
    },
    // 设置站点信息
    async setSiteInfo({ commit, state }, payload) {
      if (payload) {
        document.title = payload.siteName;
        commit(actionTypes.UPDATE_GLOBAL_SITE_INFO, payload);
      } else {
        if (state.siteInfo.siteName) {
          document.title = state.siteInfo.siteName;
        } else {
          try {
            const { code, data } = await getSiteInfo();
            if (code === 200) {
              document.title = data.siteName;
              commit(actionTypes.UPDATE_GLOBAL_SITE_INFO, data);
            }
          } catch (error) {}
        }
      }
    },
    // 设置初始信息
    async setSiteInitInfo({ commit }, payload) {
      const { code, data } = await getInitInfo();
      if (code == 200) {
        document.title = data.siteName;
        commit(actionTypes.UPDATE_GLOBAL_INIT_INFO, data);
      }
    }
  }
};
